<?php
namespace app\common\job;

use app\common\model\Cookie;
use app\common\model\UserMain;
use app\common\model\WebSiteCookie;
use think\facade\Cache;
use think\queue\Job;

class SyncCookie
{

    public function fire(Job $job, $data)
    {

        echo '开始同步cookie' . PHP_EOL;

        $sync_time = Cache::get('sync_time');

        $now          = time();
        if (empty($sync_time) || $sync_time + 60 < $now) {

            $mysql = $this->database_();

            $cookie = $mysql->query('select * from cookie where id = 1')->fetch(\PDO::FETCH_ASSOC);

            if (empty($cookie)) return;

            $content = $cookie['content'];

            $this->setCookieFile($content);

            Cache::set('sync_time', $now);

            $mysql = null;

            echo '同步完成' . PHP_EOL;
        }else{
            return;
        }
    }


    private function database_(){


        $dsn="mysql:dbname=huke;host=47.100.126.181";

        $db = new \PDO($dsn, "huke", "2PTwDb67RxNbDSYY");

        return $db;
    }

    public function failed($data)
    {
    }

    protected function setCookieFile($cookieContent, $cookieId = 1, $websiteUrlRegular = 'huke88.com'){

        $cookie_data = '';

        foreach (explode(';', $cookieContent) as $value) {
            $value   = trim($value);
            $first_k = stripos($value, '=');
            if ($first_k === false) {
                continue;
            }
            $cookie_key = trim(substr($value, 0, $first_k));
            $cookie_val = trim(substr($value, $first_k + 1));

            if (substr($cookie_key, 0, 7) == 'Hm_lvt_' || substr($cookie_key, 0, 8) == 'Hm_lpvt_' || substr($cookie_key, 0, 5) == '_csrf') {
                continue;
            }
            $content[] = $cookie_key . '=' . $cookie_val;
            $cookie_data .= '.' . $websiteUrlRegular . '	TRUE	/	FALSE	' . (time() + 2592000) . '	' . $cookie_key . '	' . $cookie_val . PHP_EOL;
        }

        $path = runtime_path() . '/site_cookie/cookie_' . $cookieId;

        if (!file_exists(dirname($path))) {
            mkdir($path, 0777, true);
        }

        file_put_contents($path, $cookie_data);

        $siteCookie = Cookie::where('id', '=', $cookieId)->find();

        $siteCookie->content = $content;

        $siteCookie->save();

        return $cookie_data;
    }

}
